package net.yihang.server;


import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {

    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(10002);
        System.out.println("服务已就绪");

        ExecutorService service = Executors.newCachedThreadPool();

        while (true) {
            Socket socket = server.accept();
            service.execute(() -> {
                InputStream is = null;
                try {
                    is = socket.getInputStream();
                    byte[] bytes;
                    int first = is.read();
                    if (first == -1) {
                        return;
                    }
                    int second = is.read();
                    int length = (first << 8) + second;
                    bytes = new byte[length];
                    is.read(bytes);
                    System.out.println(new String(bytes, "utf-8"));
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                        }
                    }
                    try {
                        socket.close();
                    } catch (IOException e) {
                    }
                }
            });
        }
    }
}
